﻿using CnBlogsClient.ViewModels;
using CnBlogsCore.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace CnBlogsClient.Views.Articles
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class KbArticleDetailsPage : ContentPage
    {
        KbArticleDetailsViewModel ViewModel => vm ?? (vm = BindingContext as KbArticleDetailsViewModel);
        KbArticleDetailsViewModel vm;
        KbArticleDetail articles;

        public KbArticleDetailsPage(KbArticle kbArticles)
        {
            InitializeComponent();
            NavigationPage.SetHasNavigationBar(this, true);
            Title = kbArticles.Title;

            articles = new KbArticleDetail();
            this.articles.Id = kbArticles.Id;
            this.articles.Title = kbArticles.Title;
            this.articles.Summary = kbArticles.Summary;
            this.articles.Author = kbArticles.Author;
            this.articles.ViewCount = kbArticles.ViewCount;
            this.articles.DiggCount = kbArticles.DiggCount;
            this.articles.DateAdded = kbArticles.DateAdded;

            BindingContext = new KbArticleDetailsViewModel(articles);

            formsWebView.OnContentLoaded += delegate (object sender, EventArgs e)
            {
                RefreshKbArticles();
            };
        }

        async void RefreshKbArticles()
        {
            IsoDateTimeConverter iso = new IsoDateTimeConverter
            {DateTimeFormat = "yyyy-MM-dd"};
            var question = JsonConvert.SerializeObject(await ViewModel.RefreshKbArticlesAsync(), iso);
            await formsWebView.InjectJavascriptAsync("updateModel(" + question + ");");
        }

        void OnReloadKbArticles(object sender, EventArgs args)
        {
            RefreshKbArticles();
        }
    }
}